package com.wang.vedio;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.vondear.rxtool.view.RxToast;
import com.wang.vedio.application.APP;
import com.wang.vedio.fragment.GameFragment;
import com.wang.vedio.fragment.PersonalCenterFragment;
import com.wang.vedio.fragment.SearchFragment;
import com.wang.vedio.fragment.MainFragment;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.permission.MPermission;
import com.wang.vedio.permission.annotation.OnMPermissionDenied;
import com.wang.vedio.permission.annotation.OnMPermissionGranted;
import com.wang.vedio.permission.annotation.OnMPermissionNeverAskAgain;
import com.wang.vedio.utils.NotificationUtil;
import com.wang.vedio.utils.statusbar.StatusBarUtil;
import com.wang.vedio.view.XRadioGroup;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class MainActivity2 extends AppCompatActivity implements XRadioGroup.OnCheckedChangeListener {
    private void requestBasicPermission() {
        MPermission.with(MainActivity2.this).setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {

    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        RxToast.normal("部分权限开启失败，可能会影响操作");
    }

    /**
     * 基本权限管理
     */
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };
    public static AlertDialog mLoginAlert;
    public static AlertDialog.Builder mLoginBuider;


    @BindView(R.id.ly_content)
    FrameLayout lyContent;
    @BindView(R.id.rg_tab_bar)
    XRadioGroup rg_tab_bar;
    @BindView(R.id.btn_index)
    RadioButton btn_index;
    @BindView(R.id.btn_xsfx)
    RadioButton btn_xsfx;
    @BindView(R.id.btn_dcqz)
    RadioButton btn_dcqz;
    @BindView(R.id.btn_me)
    RadioButton btn_me;


    private FragmentManager fManager;
    private FragmentTransaction fTransaction;
    private Fragment fg1;
    private Fragment fg2;
    private Fragment fg3;
    private Fragment fg4;
    //退出时的时间
    private long mExitTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout);
        APP.getInstance().add(this);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBar(this, true, R.color.transparent, false, false);
        initFragments(savedInstanceState != null);
        initView();
    }

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出到后台
     */
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity2.this, "再按一次进入后台", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
        }
    }


    @Override
    public void onCheckedChanged(XRadioGroup group, @IdRes int checkedId) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        System.out.println(getSupportFragmentManager().getFragments().size() + "个fragment");
        hideAllFragment(ft);
        for (Fragment f : getSupportFragmentManager().getFragments()) {
            if (TextUtils.equals(f.getTag(), String.valueOf(checkedId))) {
                ft.show(f);
                break;
            }
        }
        ft.commitAllowingStateLoss();
    }

    //隐藏所有Fragment
    private void hideAllFragment(FragmentTransaction fragmentTransaction) {
        if (fg1 != null) fragmentTransaction.hide(fg1);
        if (fg2 != null) fragmentTransaction.hide(fg2);
        if (fg3 != null) fragmentTransaction.hide(fg3);
        if (fg4 != null) fragmentTransaction.hide(fg4);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(fg4 != null){
            fg4.onActivityResult(10,RESULT_OK,data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initFragments(boolean clearInfo) {
        fTransaction = getSupportFragmentManager().beginTransaction();
        if (clearInfo) {
            for (Fragment f : getSupportFragmentManager().getFragments()) {
                fTransaction.remove(f);
            }
        }
        fg1 = new MainFragment();
        fg2 = new SearchFragment();
        fg3 = new GameFragment();
        fg4 = new PersonalCenterFragment();
        fTransaction.add(R.id.ly_content, fg1, String.valueOf(R.id.btn_index))
                .add(R.id.ly_content, fg2, String.valueOf(R.id.btn_xsfx))
                .add(R.id.ly_content, fg3, String.valueOf(R.id.btn_dcqz))
                .add(R.id.ly_content, fg4, String.valueOf(R.id.btn_me))
                .commitNow();
    }

    private boolean canSign = false;
    public boolean isCanSign(){
        return canSign;
    }

    private void isNeedSign(){
        SubscriberOnNextListener<BaseBean<Boolean>> onNextListener = baseBean -> {
            canSign = baseBean.getData();
        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().isNeedSign(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void initView() {
        fManager = getSupportFragmentManager();
        rg_tab_bar.setOnCheckedChangeListener(this);
        //获取第一个单选按钮，并设置其为选中状态
        requestBasicPermission();
        //通知权限判断
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否需要开启通知栏功能
            NotificationUtil.OpenNotificationSetting(this, new NotificationUtil.OnNextLitener() {
                @Override
                public void onNext(int type) {
                    //获取版本信息

                }
            });
        }

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        System.out.println(getSupportFragmentManager().getFragments().size() + "个fragment");
        hideAllFragment(ft);
        for (Fragment f : getSupportFragmentManager().getFragments()) {
            if (TextUtils.equals(f.getTag(), String.valueOf(R.id.btn_index))) {
                ft.show(f);
                break;
            }
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isNeedSign();
    }


}
